use wasm_bindgen::JsCast;
use web_sys::{HtmlElement, MouseEvent};
use yew::{function_component, html, Callback, Children, Html, Properties};

#[derive(Properties, PartialEq, Clone)]
pub struct ModalProp {
    pub id: String,
    pub class: Option<String>,
    pub title: String,
    pub children: Children,
}

#[function_component(Modal)]
pub fn modal(props: &ModalProp) -> Html {
    let id = props.id.clone();
    let close_click = Callback::from(move |event: MouseEvent| {
        hide_modal(id.as_str());
        event.prevent_default();
    });

    html! {
        <div id={ props.id.clone() } class="modal-overlay">
            <div class="modal">
                <div class="modal-header">
                    <div class="title">{ props.title.clone() }</div>
                    <div class="control">
                        <button onclick={ close_click.clone()}>{ "X" } </button>
                    </div>
                </div>
                <div class="modal-body">
                    { for props.children.iter() }
                </div>
            </div>
        </div>
    }
}

pub fn show_modal(id: &str) {
    modal_css(id, "flex", "block");
}

pub fn hide_modal(id: &str) {
    modal_css(id, "none", "none");
}

fn modal_css(id: &str, modal_overlay_css: &'static str, modal_child_css: &'static str) {
    if let Some(window) = web_sys::window() {
        if let Some(document) = window.document() {
            // 查找所有关闭按钮并触发点击
            if let Some(element) = document.get_element_by_id(&id) {
                log::info!("get modal overlay: {}", id);
                let modal_overlay: &HtmlElement = element.dyn_ref::<HtmlElement>().unwrap();
                let modal_overlay_style = modal_overlay.style();
                modal_overlay_style.set_property("display", modal_overlay_css).unwrap();

                let collection = modal_overlay.get_elements_by_class_name("modal");
                if let Some(modal) = collection.get_with_index(0) {
                    log::info!("get modal: {}", id);
                    let modal: &HtmlElement = modal.dyn_ref::<HtmlElement>().unwrap();
                    let modal_style = modal.style();
                    modal_style.set_property("display", modal_child_css).unwrap();
                }
            }
        }
    }
}